#include <QStringList>
#include "factorynode.h"



FactoryNode::FactoryNode() : Node("_Factory")
{
    this->lastNode = 0;
}

bool FactoryNode::addNode(Node* node)
{
//    if(this->lastNode == 0) // Si es el primer nodo, lo inserto
//    {
//        Node::addNode(node);
//    } else // Si no es el primero
//    {
    Node* ndFind = searchNode(node); // Lo busco en la lista principal. Si no está lo inserto.
    if(ndFind == 0)
    {
        Node::addNode(node);
    } else
    {
        node = ndFind;
    }

    Node* ndFindLast = searchNode(lastNode);
    if(lastNode != 0)
    {
        ndFindLast->addNode(node);
    }
   // }

    lastNode = node;
    return true;
}

void FactoryNode::readTextFile(const QString name)
{
    QTime tim(0, 0, 0);
    //QTime tstart = tim.currentTime();
    qDebug() << "Time Start to load text file: " <<  tim.currentTime().toString();

    QFile file(name);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Error no encuentro el fichero\n";
        //return 1;
    }

    this->lastNode = 0;
    while (!file.atEnd())
    {

        QByteArray line = file.readLine();
        QList<QByteArray> lineBa = line.split(' ');
        for(int i = 0; i < lineBa.size(); i ++)
        {
            QString word = lineBa.at(i);

            if(isValidWorld(word))
            {
                word = formatWord(word);
                addNode(new Node(word));
            }
        }
    }
    qDebug() << "Time end to load text file: " <<  tim.currentTime().toString();
}

void FactoryNode::readText(const QString text)
{
     this->lastNode = 0;
     QStringList sl = text.split(' ');
     for(int i = 0; i < sl.size(); i ++)
     {
         QString word = sl.at(i);

         if(isValidWorld(word))
         {
             word = formatWord(word);
             addNode(new Node(word));
         }
     }
}

bool FactoryNode::saveFile(const QString name)
{
    bool ret = false;
    QFile fileout(name);
    if (fileout.open(QIODevice::WriteOnly))
    {
        this->save(&fileout);
        for(qint32 i = 0; i < this->getCountWords(); i++)
        {
            Node* node = this->getNode(i);
            if(node != 0)
            {
                node->save(&fileout);
            }
        }

        fileout.close();
        ret = true;
    } else
    {
        qDebug() << "Error no puedo crear el fichero " << name;
    }

    return ret;
}

bool FactoryNode::loadFile(const QString name)
{
    QTime tim(0, 0, 0);
    QTime tstart = tim.currentTime();
    qDebug() << "Time Start to load binary file: " <<  tim.currentTime().toString();
    bool ret = false;
    QFile file(name);

    if (file.open(QIODevice::ReadOnly))
    {
        this->load(&file);
        for(qint32 i = 0; i < this->getCountWords(); i++)
        {
            this->load(&file);
        }
    }

   qDebug() << "Time end to load binary file: " <<  tim.currentTime().toString();

    return ret;
}

QString FactoryNode::formatWord(QString word)
{
    word = word.remove('"');
    word = word.remove('»');
    word = word.remove('«');
    word = word.remove("?");
    word = word.remove('¿');
    word = word.remove("!");
    word = word.remove("¡");
    word = word.remove("(");
    word = word.remove(")");
    return word;
}

bool FactoryNode::isValidWorld(QString word)
{
    bool ret = false;
    if(word.size() > 0)
    {
        ret = true;
    }

    return ret;
}

QString FactoryNode::makeText(int words)
{
    QString text;
    //Node* node = getRandomNode();
    Node* node = searchStartNode();
    if(node != 0)
    {
        //Node *node = searchNode(new Node("o"));

        text += node->getKey() + " ";
        //for(int i = 0; i< words; i++)
        int i = 0;
        while(true)
        {
            node = node->getRandomNode();
            //qDebug("Nodo obtenido ok");
            if(node == 0)
            {
                qDebug("Se ha llegado a una palabra sin sucesora. Se termina la frase");
                //text += lastNode->getKey();
                break;
            } else
            {
                if(i > words)
                {
                    if(node->getKey().right(1).contains("."))
                    {
                        qDebug() << "Candidata para acabar: " << node->getKey();
                        text += node->getKey();
                        qDebug() << "Palabras: " << i;
                        break;

                    }
                }
                text += node->getKey() + " ";
                //qDebug() << text;
            }
            i++;
        }
    }
    //qDebug() << text;
    return text;
}

Node* FactoryNode::searchStartNode()
{
    Node* node = 0;
    while(true)
    {
        node = getRandomNode();
        if(node != 0)
        {
            QString firstLetter = node->getKey().left(1);
            if(firstLetter.compare(firstLetter.toUpper()) == 0) //Si la primera letra es  mayuscula
            {
                qDebug() << "firstLetter: " << firstLetter;
                qDebug() << "firstLetter.toUpper(): " << firstLetter.toUpper();
                break;
            }
        } else
        {
            qDebug() << "searchStartNode. Node not found ";
            break;
        }
    }
    return node;
}


